import { onHide, onShow } from '@dcloudio/uni-app';
import { ref } from 'vue';
import { BooleanNumber } from '@/enums';
import { useIntervalFn } from '@/hooks/useIntervalFn';
import { isApp } from '@/utils/platform.utils';

export function useReadCard() {
  let readerPlugin;
  // #ifdef APP-PLUS
  // eslint-disable-next-line prefer-const
  readerPlugin = uni.requireNativePlugin('XWC-Reader');
  console.log('>>>readerPlugin', readerPlugin);
  // #endif

  const readDeviceInit = ref(false);

  const initReadDevice = () => {
    if (readDeviceInit.value) {
      return Promise.resolve();
    }
    return new Promise((resolve, reject) => {
      readerPlugin.init(data => {
        if (data.success === BooleanNumber.TRUE) {
          readDeviceInit.value = true;
          resolve(data);
        }
        else {
          readDeviceInit.value = false;
          console.log('>>>读卡设备开启失败', data);
          reject(data);
        }
      });
    });
  };

  const openDevice = () => {
    if (!isApp)
      return;

    if (!readDeviceInit.value) {
      initReadDevice();
    }
  };

  const closeDevice = () => {
    if (!isApp)
      return;
    cleanup();
    // readerPlugin.free();
    readDeviceInit.value = false;
  };

  const taskList: (() => void)[] = [];
  const cleanup = () => {
    taskList.forEach(task => task());
    taskList.length = 0;
  };

  const createReadTask = async <T = any>(
    executor: () => Promise<T>,
    interval = 1000
  ): Promise<T> => {
    if (!isApp) {
      return Promise.reject(new Error('is not app'));
    }

    if (!readDeviceInit.value) {
      await initReadDevice();
    }

    return new Promise((resolve, reject) => {
      const { pause } = useIntervalFn(() => {
        executor().then(resolve).catch(reject);
      }, interval);

      taskList.push(pause);
    });
  };

  // 读取身份证
  const readCard = (interval = 1000) => {
    return createReadTask(() => {
      return new Promise<any>(resolve => {
        readerPlugin.ReadIDCard(res => {
          if (res.success === BooleanNumber.TRUE) {
            // 蜂鸣声
            readerPlugin.beep();
            stopReadCard();
            resolve(res.data);
          }
        });
      });
    }, interval);
  };

  // 扫描二维码
  const readQrcode = () => {
    return new Promise<string>((resolve, reject) => {
      readerPlugin.ScanAct(res => {
        if (res.success === BooleanNumber.TRUE) {
          stopReadCard();
          resolve(res.data);
        }
        else {
          reject(res);
        }
      });
      taskList.push(() => {
        readerPlugin.CancelScan();
      });
    });
  };

  // 读取银行卡-接触式IC
  const readBankCardIC = () => {
    return new Promise(resolve => {
      readerPlugin.ReadBankCard_IC(res => {
        if (res.success === BooleanNumber.TRUE) {
          readerPlugin.beep();
          stopReadCard();
          resolve({ data: res.data, type: 'bankCardIC' });
        }
      });
    });
  };

  // 读取银行卡-非接触式IC
  const readBankCardPIC = () => {
    return createReadTask(() => {
      return new Promise(resolve => {
        readerPlugin.ReadBankCard_PIC(res => {
          if (res.success === BooleanNumber.TRUE) {
            readerPlugin.beep();
            stopReadCard();
            resolve({ data: res.data, type: 'bankCardPIC' });
          }
        });
      });
    });
  };

  // 读取银行卡-刷磁条
  const readBankCardMag = () => {
    return new Promise(resolve => {
      readerPlugin.ReadBankCard_Mag(res => {
        // TODO
        console.log('>>>>ReadBankCard_Mag', res);
        if (res.success === BooleanNumber.TRUE) {
          readerPlugin.beep();
          stopReadCard();
          resolve({ data: res.data, type: 'bankCardMag' });
        }
      });
      taskList.push(() => {
        console.log('>>移除磁条监听');
        readerPlugin.CancelReadMagCard();
        console.log('>>移除磁条监听成功');
      });
    });
  };

  // 读取二代社保卡
  const readSciCard = () => {
    return createReadTask(() => {
      return new Promise(resolve => {
        readerPlugin.ReadSciCard(res => {
          if (res.success === BooleanNumber.TRUE) {
            stopReadCard();
            resolve({ data: res.data, type: 'sciCard' });
          }
        });
      });
    });
  };

  // 读取三代社保卡
  const readSciCard3G = () => {
    return createReadTask(() => {
      return new Promise(resolve => {
        readerPlugin.ReadSciCard3G(res => {
          if (res.success === BooleanNumber.TRUE) {
            stopReadCard();
            resolve({ data: res.data, type: 'sciCard3G' });
          }
        });
      });
    });
  };

  const stopReadCard = () => {
    cleanup();
  };

  onShow(() => {
    openDevice();
  });

  onHide(() => {
    closeDevice();
  });

  return {
    openDevice,
    closeDevice,
    readCard,
    stopReadCard,
    readQrcode,
    readBankCardIC,
    readBankCardPIC,
    readBankCardMag,
    readSciCard,
    readSciCard3G
  };
}
